package com.hice.demo.sbdbra.common.session;

import com.hice.demo.sbdbra.common.util.security.MD5Util;
import org.apache.commons.lang3.StringUtils;

import java.util.Random;

public class SessionIdGenerator {
    private static final int SESSION_ID_LENGTH = 16;
    private static String appServiceName = "GBT_APP";

    private static Random randomizer = new Random();

    public static String generateSessionId() {
        byte[] random = new byte[16];

        StringBuilder buffer = new StringBuilder();
        int resultLenBytes = 0;

        while (resultLenBytes < 16) {
            randomizer.nextBytes(random);

            for (int j = 0; (j < random.length) && (resultLenBytes < 16); j++) {
                byte b1 = (byte) ((random[j] & 0xF0) >> 4);
                byte b2 = (byte) (random[j] & 0xF);
                if (b1 < 10)
                    buffer.append((char) (48 + b1));
                else
                    buffer.append((char) (65 + (b1 - 10)));
                if (b2 < 10)
                    buffer.append((char) (48 + b2));
                else
                    buffer.append((char) (65 + (b2 - 10)));
                resultLenBytes++;
            }
        }

        buffer.append('.').append(appServiceName);

        return buffer.toString();
    }

    public static String generateSessionId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return generateSessionId();
        }
        String str = "";
        for (int i = 0; i < userId.length(); i++) {
            str = new StringBuilder().append(str).append(MD5Util.MD5(userId.substring(i)).substring(8, 24)).toString();
        }
        StringBuilder buffer = new StringBuilder();
        buffer.append(MD5Util.MD5(str).toUpperCase());
        buffer.append('.').append(appServiceName);
        return buffer.toString();
    }

    public void setAppServiceName(String appServiceName) {
        appServiceName = appServiceName;
    }
}